/**
 * 出库操作storeOutRecord.js
 * 版本号： v1.0.0
 */
var searchBtnId = "";
var buildBtnId = "";
var confirmBtnId = "";
var cancelBtnId = "";
$(function () {
    /**
     * 出库操作
     */
    var lastChecked = 0;
    var coId = $('#coId').val();
    $("#storeOutRecord_dataList").datagrid({
        fit: true,
        fitColumns: true,
        method: "POST",
        singleSelect: true,
        border: false,
        striped: true,
        url: CONTEXT_PATH + '/store/storeDetailList.do?coId='+coId,
        idField: 'stId',
        columns: [
            [
                {field: 'origIndex', title: '序列', width: 25, fixed: true},
                {field: 'newIndex', title: '序列', width: 25, fixed: true,hidden:true},
                {field: 'material', title: '材料名称', width: 160, fixed: true,
                    formatter:function(value){
                        if(value){
                            return value.materialName;
                        }
                    }},
                {field: 'standardType_', title: '材料规格', width: 160, fixed: true,
                    formatter:function(value,row){
                        if(row.material){
                            return row.material.standardType;
                        }
                    }},
                {field: 'storeNum', title: '库存数量', width: 80, fixed: true},
                {field: 'meteringUnit_', title: '计量单位', width: 80, fixed: true,
                    formatter:function(value,row){
                        if(row.material){
                            return row.material.meteringUnit;
                        }
                    }},
                {
                    field: 'supplier', title: '材料供应商', width: 120,fixed: true,
                    formatter: function (value) {
                        if (value) {
                            return value.supName;
                        }
                    }
                },
                {field: 'pullDate', title: '出库时间', width: 130, fixed: true,hidden:true},
                {field: 'stoNum', title: '本次出库', width: 80,fixed: true,editor:{type:'numberbox'},
                    formatter:function(val,row){
                        var storeNum = row.storeNum;
                        if(val){
                            if(val > storeNum){
                                $.messager.show({ title:"系统提示", msg: "出库数量不能大于库存数量", timeout:3000, showType:"slide" });
                                return 0;
                            }else{
                                return val;
                            }
                        }
                    }
                },
                {field: 'purpose', title: '材料用途', width: 150,fixed: true,editor:{type:'textbox'}},
                {field: 'pullPerson', title: '出库人员', width: 20,hidden:true,editor:{type:'textbox'}},
            ]
        ],
        onCheck: function (rowIndex, rowData) {
            var row = $("#storeOutRecord_dataList").datagrid("getChecked");
            if (row && rowIndex == lastChecked) {
                $('#storeOutRecord_dataList').datagrid("unselectAll");//取消选中当前所有行
                lastChecked = null;
            } else {
                lastChecked = rowIndex;
            }
        },
        onLoadSuccess: function (data) {
            if (data.rows.length > 0) {
                lastChecked = null;
                $("#storeOutRecord_dataList").datagrid("selectRow", 0);
            }
            //加载成功启用编辑
            var len = data.rows.length;
            for(var i = 0; i < len; i++){
                $("#storeOutRecord_dataList").datagrid("beginEdit", i);
            }
        }
    });


    //定义可操作按钮
    $("#storeOutRecord_menu").dialog({
        title: '',
        width: 'auto',
        height: 35,
        closed: false,
        cache: false,
        inline: true,
        modal: false,
        border: false,
        toolbar: createToolbar()
    });

    hideToolbar("addList");

});

/**
 * 隐藏指定的toolBar
 */
function  hideToolbar(state) {
    //添加出库时
    if(state == "addList"){
        $('#'+confirmBtnId).parent("td").hide();
        $('#'+cancelBtnId).parent("td").hide();
        $('#storeOutList').hide();
        $('#'+buildBtnId).parent("td").show();
        $('#'+searchBtnId).parent("td").show();
        $('#materialNameTd').show();
        $('#standardTypeTd').show();
    }
    //生成出库单时
    if(state == "buildList"){
        $('#'+confirmBtnId).parent("td").show();
        $('#'+cancelBtnId).parent("td").show();
        $('#'+buildBtnId).parent("td").hide();
        $('#'+searchBtnId).parent("td").hide();
        $('#storeOutList').show();
        $('#materialNameTd').hide();
        $('#standardTypeTd').hide();
    }

}
/**
 * 创建toolbar按钮组
 * @returns {Array}
 */
function createToolbar() {
    var toolbar = [];
    var falg = false;
    for (var j = 0; j < btnOptions.length; j++) {
        if (false != btnOptions[j].value) {
            falg = true;
            break;
        }
    }
    if (!falg) {
        //不存在按钮
        toolbar.push({});
    } else {
        //存在按钮
        for (var i = 0; i < btnOptions.length; i++) {
            if (false != btnOptions[i].value) {
                //查询按钮
                if ("searchBtn" == btnOptions[i].key) {
                    searchBtnId = btnOptions[i].value.meId;
                    toolbar.push({
                        id: btnOptions[i].value.meId,
                        text: btnOptions[i].value.name,
                        iconCls: btnOptions[i].value.iconCls,
                        handler: function () {
                            storeDetail_loadSearch();
                        }
                    });
                }
                //生成出库单
                if ("buildBtn" == btnOptions[i].key) {
                    buildBtnId = btnOptions[i].value.meId;
                    toolbar.push({
                        id: btnOptions[i].value.meId,
                        text: btnOptions[i].value.name,
                        iconCls: btnOptions[i].value.iconCls,
                        handler: function () {
                            buildPull();
                        }
                    });
                }
                //确认出库
                if ("confirmBtn" == btnOptions[i].key) {
                    confirmBtnId = btnOptions[i].value.meId;
                    toolbar.push({
                        id: btnOptions[i].value.meId,
                        text: btnOptions[i].value.name,
                        iconCls: btnOptions[i].value.iconCls,
                        handler: function () {
                            confirmPull(this);
                        }
                    });
                }
                //返回
                if ("cancelBtn" == btnOptions[i].key) {
                    cancelBtnId = btnOptions[i].value.meId;
                    toolbar.push({
                        id: btnOptions[i].value.meId,
                        text: btnOptions[i].value.name,
                        iconCls: btnOptions[i].value.iconCls,
                        handler: function () {
                            cancelFun();
                        }
                    });
                }
            }
        }
    }
    return toolbar;
}

/**
 *  加载查询
 */
function storeDetail_loadSearch() {
    $("#storeOutRecord_dataList").datagrid("reload", {
        materialName: $("#materialName").textbox("getValue"),
        standardType: $("#standardType").textbox("getValue")
    });
}

/**
 * 生成出库单
 */
function buildPull(){
    //结束编辑
    var rows = $('#storeOutRecord_dataList').datagrid("getRows");
    for(var i = 0; i < rows.length; i++){
        $('#storeOutRecord_dataList').datagrid('endEdit', i);
    }
    //显示出库单
    var columns = $('#storeOutRecord_dataList').datagrid("options").columns;
    var pullList = $('#storeOutRecord_dataList').datagrid('getChanges','updated');
    //存在出库数量大于库存数量则返回
    for(var i=0;i<pullList.length;i++){
        //库存数量
        var storeNum = pullList[i].storeNum;
        //出库数量
        var stoNum = pullList[i].stoNum;
        if(stoNum){
            if(stoNum > storeNum){
                $.messager.show({ title:"系统提示", msg: "存在出库数量大于库存数量！", timeout:3000, showType:"slide" });
                for(var i = 0; i < pullList.length; i++){
                    $("#storeOutRecord_dataList").datagrid("beginEdit", i);
                }
                return;
            }
        }
    }
    if(pullList.length > 0){
        //获取当前时间
        var pullDate = getFormatDate();
        //存储需显示的行标
        var mIndex = new Map();
        //显示新序列及出库时间列
        $('#storeOutRecord_dataList').datagrid('showColumn', 'newIndex');
        $('#storeOutRecord_dataList').datagrid('showColumn', 'pullDate');
        //隐藏原序列及库存数量列
        $('#storeOutRecord_dataList').datagrid('hideColumn', 'origIndex');
        $('#storeOutRecord_dataList').datagrid('hideColumn', 'storeNum');
        //设置列不允许编辑 stoNum purpose pullPerson
        var stoNum = $("#storeOutRecord_dataList").datagrid('getColumnOption', 'stoNum');
        var purpose = $("#storeOutRecord_dataList").datagrid('getColumnOption', 'purpose');
        var pullPerson = $("#storeOutRecord_dataList").datagrid('getColumnOption', 'pullPerson');
        stoNum.editor = {};
        purpose.editor = {};
        pullPerson.editor = {};
        //隐藏查询条件及相应按钮
        hideToolbar("buildList");
        for(var i=0;i<pullList.length;i++){
            var stoNum = pullList[i].stoNum;
            if(stoNum != "" && stoNum != null){
                var index = $("#storeOutRecord_dataList").datagrid("getRowIndex",pullList[i]);
                mIndex.set(index,index);
            }
        }
        var totalRow = $("#storeOutRecord_dataList").datagrid('getRows').length;
        //新序列
        var newIndex = 0;
        for(var j=0;j<totalRow;j++){
            var showIndex = mIndex.get(j);
            if(typeof(showIndex) != "undefined"){ //显示行
                //创建新的序列
                pullList[showIndex][columns[0][1].field]= newIndex + 1;
                //创建出库时间
                pullList[showIndex][columns[0][7].field]= pullDate;
                $('#storeOutRecord_dataList').datagrid('refreshRow', showIndex);
                newIndex ++;
            }else{  //隐藏行
                $('#datagrid-row-r1-2-'+j).hide();
            }
        }
    }
}

/**
 * 返回添加出库
 */
function cancelFun(){
    //显示查询条件及相应按钮
    hideToolbar("addList");
    //隐藏新序列及出库时间列
    $('#storeOutRecord_dataList').datagrid('hideColumn', 'newIndex');
    $('#storeOutRecord_dataList').datagrid('hideColumn', 'pullDate');
    //显示原序列及库存数量列
    $('#storeOutRecord_dataList').datagrid('showColumn', 'origIndex');
    $('#storeOutRecord_dataList').datagrid('showColumn', 'storeNum');
    //设置列允许编辑 stoNum purpose pullPerson
    var stoNum = $("#storeOutRecord_dataList").datagrid('getColumnOption', 'stoNum');
    var purpose = $("#storeOutRecord_dataList").datagrid('getColumnOption', 'purpose');
    var pullPerson = $("#storeOutRecord_dataList").datagrid('getColumnOption', 'pullPerson');
    stoNum.editor = {type:'numberbox'};
    purpose.editor = {type:'textbox'};
    pullPerson.editor = {type:'textbox'};
    //返回时开启编辑
    var rows = $('#storeOutRecord_dataList').datagrid("getRows");
    for(var i = 0; i < rows.length; i++){
        $("#storeOutRecord_dataList").datagrid("beginEdit", i);
    }
    var totalRow = $("#storeOutRecord_dataList").datagrid('getRows').length;
    for(var j=0;j<totalRow;j++){
        $('#datagrid-row-r1-2-'+j).show();
    }
}

/**
 * 确认出库
 */
function confirmPull(objBtn) {
    $.messager.confirm("系统提示", "确定出库吗？", function(r) {
        if (r) {
            //设置按钮失效，避免表单重复提交
            $(objBtn).linkbutton("disable");
            var pullList = $('#storeOutRecord_dataList').datagrid('getChanges','updated');
            var storeOutRecordList = [];
            for(var i=0;i<pullList.length;i++){
                var stoNum = pullList[i].stoNum;
                if(stoNum != "" && stoNum != null){
                    var storeOutRecord = {
                        stId:pullList[i].stId,
                        pullDate:pullList[i].pullDate,
                        stoNum:stoNum,
                        purpose:pullList[i].purpose,
                    }
                    storeOutRecordList.push(storeOutRecord);
                }
            }
            $.ajax({
                url: CONTEXT_PATH + "/store/savePull.do",
                type: "post",
                data : JSON.stringify(storeOutRecordList),
                contentType : "application/json",
                dataType : "json",
                success: function (data) {
                    if(data.code == 'PC_200'){
                        var url = CONTEXT_PATH + "/store/index.do";
                        saveJump(data,url);
                    }else{
                        $.messager.show({ title:"系统提示", msg: "出库失败！", timeout:3000, showType:"slide" });
                    }
                },
                error:function(){
                    $.messager.show({ title:"系统提示", msg: "出库失败！", timeout:3000, showType:"slide" });
                }
            })
        }
    });
}


